package com.example.secondhandshop.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.ImageResponseData;
import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.model.FileUploader;
import com.example.secondhandshop.model.ProductService;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.imageview.ShapeableImageView;

import java.io.File;

public class AvatarActivity extends AppCompatActivity {

    // 定义常量
    private static final int REQUEST_IMAGE_GET_CONTENT = 1;
    private static final int REQUEST_PERMISSION = 1;
    private TextView tvOpenAlbum;
    private TextView tvCancel;
    private BottomSheetDialog bottomSheetDialog;
    long imageCode;
    private Uri imageUri;
    private ShapeableImageView btnChooseImage;
    private Button btnPublish;


    private final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_avater);
        Button buttonSave = findViewById(R.id.buttonSave);
        btnChooseImage = findViewById(R.id.iv_head);

//
//        //申请权限
//        if (ContextCompat.checkSelfPermission(this,
//                Manifest.permission.READ_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            if (ActivityCompat.shouldShowRequestPermissionRationale(
//                    AvatarActivity.this,
//                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
//            } else {
//                requestPermissions(PERMISSIONS_STORAGE,
//                        REQUEST_EXTERNAL_STORAGE);
//            }
//        } else {
//            buttonSave.setOnClickListener(v -> showBottomSheetDialog());
//            openGallery();
//            btnPublish.setOnClickListener(v -> publishProduct());
//        }

        ShapeableImageView ivHead = findViewById(R.id.iv_head);
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetDialog();
            }
        });

        buttonSave.setOnClickListener(v -> publishProduct());




    }


    // 声明ActivityResultLauncher，用于处理图像选择返回
    private ActivityResultLauncher<Intent> openGalleryLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                // 处理返回结果
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    Uri selectedImageUri = result.getData().getData();
                    String imagePath = getRealPathFromURI(selectedImageUri);
                    if (imagePath != null) {
                        File imageFile = new File(imagePath);
                        uploadImage(imageFile);
                    } else {
                        Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    // 显示底部对话框
    private void showBottomSheetDialog() {
        View bottomSheetView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom, null);
        bottomSheetDialog = new BottomSheetDialog(this, R.style.BottomDialog);
        bottomSheetDialog.setContentView(bottomSheetView);

        tvOpenAlbum = bottomSheetView.findViewById(R.id.tv_open_album);
        tvCancel = bottomSheetView.findViewById(R.id.tv_cancel);

        // 打开相册选项
        tvOpenAlbum.setOnClickListener(v1 -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
                // 如果已有权限，直接打开相册
                openGallery();
            }
        });

        // 取消选项
        tvCancel.setOnClickListener(v1 -> bottomSheetDialog.dismiss());

        bottomSheetDialog.show();
    }


    // 打开相册
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_GET_CONTENT);// 使用ActivityResultLauncher启动相册
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_GET_CONTENT && resultCode == RESULT_OK) {
            imageUri = data.getData();
            if (imageUri != null) {
                runOnUiThread(() -> Toast.makeText(AvatarActivity.this, "已选择图片: " + imageUri, Toast.LENGTH_SHORT).show());
                String imageFilePath = getRealPathFromURI(imageUri);
                if (imageFilePath != null) {
                    btnChooseImage.setImageURI(imageUri);
                    Log.d("AvatarActivity", "文件路径1: " + imageFilePath);
                    uploadImage(new File(imageFilePath));
                } else {
                    // 处理无法获取文件路径的情况
                    Log.e("AvatarActivity", "无法获取图片文件路径");
                }
            }
        }
    }


    private void publishProduct() {
        Item item = new Item();

        item.setImageCode(imageCode);


        ProductService productService = new ProductService();
        productService.addProduct(item, new ProductService.ProductCallback() {
            @Override
            public void onProductAdded(String message) {
                runOnUiThread(() -> {
                    Toast.makeText(AvatarActivity.this, message, Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onProductAddFailure(String error) {
                runOnUiThread(() -> Toast.makeText(AvatarActivity.this, error, Toast.LENGTH_SHORT).show());
            }
        });
    }



    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        try (Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                Log.d("AvatarActivity", "文件路径2: " + cursor.getString(column_index));
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(AvatarActivity.this, "获取图片路径失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
        return null;
    }

    private void uploadImage(File imageFile) {
        FileUploader fileUploader = new FileUploader();
        fileUploader.uploadFile(imageFile, new FileUploader.UploadCallback() {
            @Override
            public void onUploadSuccess(ImageResponseData imageResponseData) {
                runOnUiThread(() -> {
                    imageCode = imageResponseData.getImageCode();

                    Toast.makeText(AvatarActivity.this, "图片上传成功", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onUploadFailure(String error) {
                runOnUiThread(() -> Toast.makeText(AvatarActivity.this, error, Toast.LENGTH_SHORT).show());
            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(this, "需要存储权限来打开相册", Toast.LENGTH_SHORT).show();
                    openGallery();
                }
                break;
            default:
                Toast.makeText(this, "需要存储权限来打开相册", Toast.LENGTH_SHORT).show();
                break;
        }
    }

}